import json
import random
from selenium import webdriver
from selenium.webdriver.edge.options import Options

import time


def OpenUrl(url):
    # 访问网址
    driver.get(url)
    with open('cookies.txt', 'r') as f:  # 由于webdriver启动时类似无痕模式，使用带cookie的方式登录微软账号
        cookies_list = json.load(f)
        for cookie in cookies_list:
            if isinstance(cookie.get('expiry'), float):
                cookie['expiry'] = int(cookie['expiry'])
            driver.add_cookie(cookie)


def run_pc(random_number):
    OpenUrl('https://cn.bing.com/search?q=' + str(random_number))


def getScore(str, l):
    times = 0
    for i in l:
        times += 1
        run_pc(i)
        print(str + '第', times, '次完成')
        time.sleep(2)
    driver.quit()


if __name__ == "__main__":
    timesEdge = 6  # Microsoft Edge奖励次数
    timesPC = 34  # 电脑搜索次数
    timesMobile = 30  # 移动设备搜索次数
    timesSum = timesEdge + timesPC + timesMobile  # 总次数
    List = random.sample(range(1, 10000), timesSum)

    options = Options()
    # 设置driver路径
    driverPath = 'msedgedriver'

    # Microsoft Edge奖励
    driver = webdriver.Edge(driverPath, options=options)
    getScore('Edge奖励', List[:timesEdge])
    print('Microsoft Edge奖励完成')

    # 电脑搜索
    options.add_argument("--headless")  # 设置后台运行，无窗口化
    driver = webdriver.Edge(driverPath, options=options)
    getScore('电脑搜索', List[timesEdge:timesEdge + timesPC])
    print('电脑搜索完成')

    # 移动设备搜索
    with open('deviceName.txt') as f:
        deviceName = f.readline()
    mobile_emulation = {'deviceName': deviceName}  # 添加移动设备搜索
    options.add_experimental_option("mobileEmulation", mobile_emulation)  # 使用移动设备搜索模拟器打开
    driver = webdriver.Edge(driverPath, options=options)
    # 如果手机端更换设备也一直不成功，请注释掉上面三行并启用下面三行
    # options_edge = Options()
    # options_edge.add_argument("--auto-open-devtools-for-tabs")  # 打开F12
    # driver = webdriver.Edge(driverPath, options=options_edge)  # F12不能无窗口运行
    getScore('移动设备搜索', List[timesEdge + timesPC:])
    print('移动设备搜索完成')
